#!/usr/bin/env python

import component

from autorm.fields import *

class Group(component.Model):
    '''Group class
    
    @author Julot <andy.julot@gmail.com>
    @since Thursday, February 23, 2012. 09:09 AM'''
    
    class Meta:
        table = 'groups'
        pk = 'id'
        fields = [IdField('id'),
                  TextField('name', 255, index=True, collate='NOCASE'),
                  IntegerField('frequency')]
    
    @staticmethod
    def updateFrequency(oldNames, newNames):
        try: old = set(oldNames)
        except: old = set()
        try: new = set(newNames)
        except: new = set()
        added = new - old
        removed = old - new
        if added: Group.addGroups(added)
        if removed: Group.removeGroups(removed)
    
    @staticmethod
    def addGroups(groups):
        for group in groups:
            model = Group.objects.query(name=group)[0]
            if model:
                model.frequency += 1
            else:
                model = Group()
                model.name = group
                model.frequency = 1
            model.save()
    
    @staticmethod
    def removeGroups(groups):
        for group in groups:
            model = Group.objects.query(name=group)[0]
            if model:
                model.frequency -= 1
                if model.frequency < 1:
                    model.delete()
                else:
                    model.save()
    